package main.java.com.healthy.controller;
import main.java.com.healthy.entity.Food;
import main.java.com.healthy.entity.User;
import main.java.com.healthy.service.FoodService;
import main.java.com.healthy.service.impl.FoodServiceImpl;

import java.util.List;
import java.util.Scanner;

/**
 * 食物管理控制器
 * 对应功能模块：食物营养数据库模块
 */
public class FoodController {
    private FoodService foodService;
    private Scanner scanner;

    public FoodController() {
        this.foodService = new FoodServiceImpl();
        this.scanner = new Scanner(System.in);
    }

    /**
     * 管理食物
     */
    public void manageFoods(User user) {
        while (true) {
            System.out.println("\n=== 食物数据库管理 ===");
            System.out.println("1. 浏览所有食物");
            System.out.println("2. 搜索食物");
            System.out.println("3. 按类别查看食物");
            System.out.println("4. 添加新食物");
            System.out.println("5. 修改食物信息");
            System.out.println("6. 删除食物");
            System.out.println("7. 返回主菜单");
            System.out.print("请选择: ");

            String choice = scanner.nextLine().trim();

            switch (choice) {
                case "1":
                    browseAllFoods();
                    break;
                case "2":
                    searchFoods();
                    break;
                case "3":
                    browseFoodsByCategory();
                    break;
                case "4":
                    addNewFood(user);
                    break;
                case "5":
                    updateFood();
                    break;
                case "6":
                    deleteFood();
                    break;
                case "7":
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    /**
     * 浏览所有食物
     */
    private void browseAllFoods() {
        System.out.println("\n=== 所有食物 ===");

        List<Food> foods = foodService.getAllFoods();
        if (foods.isEmpty()) {
            System.out.println("食物数据库为空！");
            return;
        }

        displayFoods(foods);
        System.out.println("\n按回车键返回...");
        scanner.nextLine();
    }

    /**
     * 搜索食物
     */
    private void searchFoods() {
        System.out.println("\n=== 搜索食物 ===");
        System.out.print("请输入食物名称关键字: ");
        String keyword = scanner.nextLine().trim();

        if (keyword.isEmpty()) {
            System.out.println("搜索关键字不能为空！");
            return;
        }

        List<Food> foods = foodService.searchFoods(keyword);
        if (foods.isEmpty()) {
            System.out.println("没有找到匹配的食物！");
            return;
        }

        System.out.println("找到 " + foods.size() + " 个匹配的食物:");
        displayFoods(foods);

        System.out.println("\n按回车键返回...");
        scanner.nextLine();
    }

    /**
     * 按类别查看食物
     */
    private void browseFoodsByCategory() {
        System.out.println("\n=== 按类别查看食物 ===");

        List<String> categories = foodService.getFoodCategories();
        if (categories.isEmpty()) {
            System.out.println("没有可用的食物类别！");
            return;
        }

        System.out.println("可用的食物类别:");
        for (int i = 0; i < categories.size(); i++) {
            System.out.println((i + 1) + ". " + categories.get(i));
        }

        System.out.print("请选择类别编号: ");
        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            if (choice < 1 || choice > categories.size()) {
                System.out.println("无效的选择！");
                return;
            }

            String category = categories.get(choice - 1);
            List<Food> foods = foodService.getFoodsByCategory(category);

            System.out.println("\n=== " + category + " ===");
            displayFoods(foods);
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
        }

        System.out.println("\n按回车键返回...");
        scanner.nextLine();
    }

    /**
     * 添加新食物
     */
    private void addNewFood(User user) {
        System.out.println("\n=== 添加新食物 ===");

        System.out.print("请输入食物名称: ");
        String foodName = scanner.nextLine().trim();
        if (foodName.isEmpty()) {
            System.out.println("食物名称不能为空！");
            return;
        }

        // 检查食物是否已存在
        Food existingFood = foodService.getFoodByExactName(foodName);
        if (existingFood != null) {
            System.out.println("食物 '" + foodName + "' 已存在！");
            return;
        }

        System.out.println("请选择食物类别:");
        List<String> categories = foodService.getFoodCategories();
        for (int i = 0; i < categories.size(); i++) {
            System.out.println((i + 1) + ". " + categories.get(i));
        }
        System.out.println((categories.size() + 1) + ". 新建类别");
        System.out.print("请选择: ");

        String category;
        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            if (choice >= 1 && choice <= categories.size()) {
                category = categories.get(choice - 1);
            } else if (choice == categories.size() + 1) {
                System.out.print("请输入新类别名称: ");
                category = scanner.nextLine().trim();
            } else {
                System.out.println("无效的选择！");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
            return;
        }

        System.out.print("请输入每100g热量(千卡): ");
        double calories = getValidDoubleInput(0, 1000);

        System.out.print("请输入每100g碳水化合物(g): ");
        double carbs = getValidDoubleInput(0, 100);

        System.out.print("请输入每100g蛋白质(g): ");
        double protein = getValidDoubleInput(0, 100);

        System.out.print("请输入每100g脂肪(g): ");
        double fat = getValidDoubleInput(0, 100);

        System.out.print("请输入每100g膳食纤维(g) [可选]: ");
        String fiberInput = scanner.nextLine().trim();
        double fiber = fiberInput.isEmpty() ? 0 : Double.parseDouble(fiberInput);

        System.out.print("请输入描述 [可选]: ");
        String description = scanner.nextLine().trim();

        Food newFood = new Food();
        newFood.setFoodName(foodName);
        newFood.setCategory(category);
        newFood.setCalories(calories);
        newFood.setCarbohydrates(carbs);
        newFood.setProtein(protein);
        newFood.setFat(fat);
        newFood.setFiber(fiber);
        newFood.setDescription(description);
        newFood.setCustom(true);

        if (foodService.addFood(newFood)) {
            System.out.println("食物添加成功！");
        } else {
            System.out.println("食物添加失败！");
        }
    }

    /**
     * 修改食物信息
     */
    private void updateFood() {
        System.out.println("\n=== 修改食物信息 ===");
        System.out.print("请输入要修改的食物名称: ");
        String foodName = scanner.nextLine().trim();

        Food food = foodService.getFoodByExactName(foodName);
        if (food == null) {
            System.out.println("食物 '" + foodName + "' 不存在！");
            return;
        }

        System.out.println("当前食物信息:");
        displayFoodDetail(food);

        System.out.println("\n请输入新的信息（直接回车保持原值）:");

        System.out.print("食物名称 [" + food.getFoodName() + "]: ");
        String newName = scanner.nextLine().trim();
        if (!newName.isEmpty()) {
            food.setFoodName(newName);
        }

        System.out.print("类别 [" + food.getCategory() + "]: ");
        String newCategory = scanner.nextLine().trim();
        if (!newCategory.isEmpty()) {
            food.setCategory(newCategory);
        }

        System.out.print("热量(千卡/100g) [" + food.getCalories() + "]: ");
        String caloriesInput = scanner.nextLine().trim();
        if (!caloriesInput.isEmpty()) {
            food.setCalories(Double.parseDouble(caloriesInput));
        }

        System.out.print("碳水化合物(g/100g) [" + food.getCarbohydrates() + "]: ");
        String carbsInput = scanner.nextLine().trim();
        if (!carbsInput.isEmpty()) {
            food.setCarbohydrates(Double.parseDouble(carbsInput));
        }

        System.out.print("蛋白质(g/100g) [" + food.getProtein() + "]: ");
        String proteinInput = scanner.nextLine().trim();
        if (!proteinInput.isEmpty()) {
            food.setProtein(Double.parseDouble(proteinInput));
        }

        System.out.print("脂肪(g/100g) [" + food.getFat() + "]: ");
        String fatInput = scanner.nextLine().trim();
        if (!fatInput.isEmpty()) {
            food.setFat(Double.parseDouble(fatInput));
        }

        if (foodService.updateFood(food)) {
            System.out.println("食物信息更新成功！");
        } else {
            System.out.println("食物信息更新失败！");
        }
    }

    /**
     * 删除食物
     */
    private void deleteFood() {
        System.out.println("\n=== 删除食物 ===");
        System.out.print("请输入要删除的食物名称: ");
        String foodName = scanner.nextLine().trim();

        Food food = foodService.getFoodByExactName(foodName);
        if (food == null) {
            System.out.println("食物 '" + foodName + "' 不存在！");
            return;
        }

        System.out.println("将要删除的食物:");
        displayFoodDetail(food);

        System.out.print("确认删除？(y/n): ");
        String confirm = scanner.nextLine().trim().toLowerCase();

        if ("y".equals(confirm) || "yes".equals(confirm)) {
            if (foodService.deleteFood(food.getFoodId())) {
                System.out.println("食物删除成功！");
            } else {
                System.out.println("食物删除失败！");
            }
        } else {
            System.out.println("取消删除操作。");
        }
    }

    /**
     * 显示食物列表
     */
    private void displayFoods(List<Food> foods) {
        System.out.printf("%-4s %-20s %-10s %-8s %-8s %-8s %-8s%n",
                "序号", "食物名称", "类别", "热量", "碳水", "蛋白质", "脂肪");
        System.out.println("--------------------------------------------------------------------------------");

        for (int i = 0; i < foods.size(); i++) {
            Food food = foods.get(i);
            System.out.printf("%-4d %-20s %-10s %-8.0f %-8.1f %-8.1f %-8.1f%n",
                    i + 1,
                    food.getFoodName(),
                    food.getCategory(),
                    food.getCalories(),
                    food.getCarbohydrates(),
                    food.getProtein(),
                    food.getFat());
        }
    }

    /**
     * 显示食物详情
     */
    private void displayFoodDetail(Food food) {
        System.out.println("食物名称: " + food.getFoodName());
        System.out.println("食物类别: " + food.getCategory());
        System.out.println("热量: " + food.getCalories() + " 千卡/100g");
        System.out.println("碳水化合物: " + food.getCarbohydrates() + " g/100g");
        System.out.println("蛋白质: " + food.getProtein() + " g/100g");
        System.out.println("脂肪: " + food.getFat() + " g/100g");
        System.out.println("膳食纤维: " + food.getFiber() + " g/100g");
        System.out.println("能量来源比例 - 碳水: " + String.format("%.1f", food.getCarbPercentage()) +
                "%, 蛋白质: " + String.format("%.1f", food.getProteinPercentage()) +
                "%, 脂肪: " + String.format("%.1f", food.getFatPercentage()) + "%");
        if (food.getDescription() != null && !food.getDescription().isEmpty()) {
            System.out.println("描述: " + food.getDescription());
        }
    }

    // 辅助方法
    private double getValidDoubleInput(double min, double max) {
        while (true) {
            try {
                String input = scanner.nextLine().trim();
                double value = Double.parseDouble(input);
                if (value >= min && value <= max) {
                    return value;
                } else {
                    System.out.print("输入值应在 " + min + " 到 " + max + " 之间，请重新输入: ");
                }
            } catch (NumberFormatException e) {
                System.out.print("请输入有效的数字: ");
            }
        }
    }
}
